package com.whynot.frame.auth.shiro.exception.advice;

import com.whynot.frame.basic.common.model.APIBase;
import com.whynot.frame.basic.common.model.ErrorCode;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述: 定义全局异常:
 * 作者: chenyao
 * 日期: 2018-01-30.
 * 项目名称: curtain-whynot-shiro-jwt-server
 * 版本: 1.0.0
 * JDK: since 1.8
 */
@RestControllerAdvice
public class ExceptionController {

    // 捕捉shiro的异常
    @ExceptionHandler(ShiroException.class)
    public APIBase handleShiro(ShiroException e) {
        return new APIBase(ErrorCode.ERR_BUS_ERROR, e.getMessage(), null,false);
    }

    @ExceptionHandler(AuthenticationException.class)
    public APIBase handle401(AuthenticationException e) {
        return new APIBase(ErrorCode.ERR_UN_TOKEN, "Unauthentication: "+e.getMessage(), null,false);
    }

    @ExceptionHandler(AuthorizationException.class)
    public APIBase handle403(AuthorizationException e) {
        return new APIBase(ErrorCode.ERR_UN_AUTH, "Unauthorized: "+e.getMessage(), null,false);
    }

    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public APIBase globalException(HttpServletRequest request, Throwable e) {
        return new APIBase(ErrorCode.ERR_SYSERROR, e.getMessage(), null,false);
    }
}

